﻿#include "Seq.h"

void SeqListInit(SeqList* ps)
{
	ps->a = NULL;
	ps->capacity = 0;
	ps->size = 0;

}

void SeqListCheck(SeqList* ps)
{
	assert(ps);
	int newnum = 0;
	if (ps->capacity == ps->size)
	{
		newnum = (ps->capacity == 0) ? 4 : 2 * ps->capacity;

		int* tmp = (int*)realloc(ps->a, newnum * sizeof(SLDateType));
		if (tmp == NULL)
		{
			perror("SeqListCheck::realloc");
			return;
		}
		ps->a = tmp;
		ps->capacity = newnum;
	}
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
	assert(ps);
	SeqListCheck(ps);
	ps->a[ps->size] = x;
	ps->size++;
}

void SeqListPrint(SeqList* ps)
{
	assert(ps);
	int i = 0;
	for ( i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void SeqListPushFront(SeqList* ps, SLDateType x)
{
	assert(ps);
	SeqListCheck(ps);
	int i = 0;
	for (i = ps->size; i > 0; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[0] = x;
	ps->size++;
}

void SeqListPopFront(SeqList* ps)
{
	assert(ps && ps->size);
	int i = 0;
	for (i = 0; i < ps->size-1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps && ps->size);
	ps->size--;
}


int SeqListFind(SeqList* ps, SLDateType x)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
			return i;
	}
	return -1;
}

void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	assert(ps);
	SeqListCheck(ps);

	int i = 0;
	for (i = ps->size; i > pos ; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[pos] = x;
	ps->size++;
}


void SeqListErase(SeqList* ps, int pos)
{
	assert(ps && ps->size);
	int i = 0;
	for (i = pos; i < ps->size-1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}

void SeqListDestroy(SeqList* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

